package com.yejiali.backend.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yejiali.backend.entity.UserFollow;
import com.yejiali.backend.entity.Users;
import com.yejiali.backend.entity.vo.AtUserVO;
import com.yejiali.backend.mapper.UserFollowMapper;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.UserFollowService;
import com.yejiali.backend.service.UsersService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户关注关系表(UserFollow)表服务实现类
 *
 * @author yejiali
 * @since 2025-08-11 14:18:58
 */
@Service("userFollowService")
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {
    @Autowired
    private UsersService usersService;

     /**
      * 查询我的关注的用户
      * @param userId
      * @return
      */
     @Override
     public Response<?> queryMyFollow(Long userId) {
         //查询我的关注的用户
         QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<UserFollow>();
         queryWrapper .eq("user_id", userId);
         queryWrapper.eq("status", 0);
         List<UserFollow> userFollows = list(queryWrapper);
         //拿到他们的id
         Set<Long> followedUserIds = userFollows.stream()
                 .map(UserFollow::getFollowedUserId)
                 .collect(Collectors.toSet());
         if (followedUserIds.isEmpty()) {
             return Response.success(Collections.emptyList());
         }
         //查询关注的用户信息
         List<Users> users = usersService.listByIds(followedUserIds);
         //转换为vo
         List<AtUserVO> atUserVOS = BeanUtil.copyToList(users, AtUserVO.class);
         // 批量查询所有关注用户的关注数
         QueryWrapper<UserFollow> countQuery = new QueryWrapper<>();
         countQuery.select("followed_user_id","count(*) as followed_count")
                 .in("followed_user_id", followedUserIds)
                 .groupBy("followed_user_id");
         List<Map<String, Object>> result = this.listMaps(countQuery);
         Map<Long, Long> followCountMap = result.stream()
                 .collect(Collectors.toMap(
                         map -> Long.valueOf(map.get("followed_user_id").toString()),
                         map -> Long.valueOf(map.get("followed_count").toString())
                 ));
         for (AtUserVO userVO : atUserVOS) {
             Long followedUserId = userVO.getUserId();
             //如果第一个值为空则将关注数置为0
             Long followCount = followCountMap.getOrDefault(followedUserId, 0L);
             userVO.setFollowCount(followCount);
         }
         return Response.success(atUserVOS);
     }

     /**
      * 关注用户
      * @param userId
      * @param followedUserId
      * @return
      */
    @Override
    public Response<String> followUser(Long userId, Long followedUserId) {
     //查看是否存在关注者与被关注者
     Users user = usersService.getById(userId);
     Users followedUser = usersService.getById(followedUserId);
     if(user == null || followedUser == null){
        return Response.error(400,"参数错误");
     }
     //查看是否已关注
     QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<UserFollow>();
     queryWrapper .eq("user_id", userId);
     queryWrapper.eq("followed_user_id", followedUserId);
     UserFollow userFollow = getOne(queryWrapper);
     if(userFollow != null){
         if(userFollow.getStatus() == 0){
            return Response.error(400,"已关注");
         }
         //取消关注
         userFollow.setStatus(0);
         updateById(userFollow);
         return Response.success("关注成功");
     }
     //关注
     UserFollow follow = new UserFollow();
     follow.setUserId(userId);
     follow.setFollowedUserId(followedUserId);
     save(follow);
     return Response.success("关注成功");
    }

     /**
      * 取消关注用户
      * @param userId
      * @param followedUserId
      * @return
      */
    @Override
    public Response<String> unfollowUser(Long userId, Long followedUserId) {
        //查看是否存在关注者与被关注者
        Users user = usersService.getById(userId);
        Users followedUser = usersService.getById(followedUserId);
        if(user == null || followedUser == null){
            return Response.error(400,"参数错误");
        }
        //查看是否已关注
        QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<UserFollow>();
        queryWrapper .eq("user_id", userId);
        queryWrapper.eq("followed_user_id", followedUserId);
        UserFollow userFollow = getOne(queryWrapper);
        if(userFollow == null){
            return Response.error(400,"未关注");
        }
        //取消关注
        userFollow.setStatus(1);
        updateById(userFollow);
        return Response.success("取消关注成功");
    }


 }


